import router, { resetRouter } from './router';
import store from './store';
import storage from 'store';
import NProgress from 'nprogress'; // progress bar
import '@/components/NProgress/nprogress.less'; // progress bar custom style
import notification from 'ant-design-vue/es/notification';
import { setDocumentTitle, domTitle } from '@/utils/domUtil';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { i18nRender } from '@/locales';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const allowList = ['login', 'register', 'registerResult']; // no redirect allowList
const loginRoutePath = '/user/login';
const defaultRoutePath = '/dashboard/workplace';

router.beforeEach(async(to, from, next) => {
  NProgress.start(); // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`);
  /* has token */
  const token = storage.get(ACCESS_TOKEN);
  if (token) {
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath });
      NProgress.done();
    } else {
      // check login user.roles is null
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        next();
      } else {
        try {
          const res = await store.dispatch('user/GetInfo');
          // request login userInfo
          // 根据用户权限信息生成可访问的路由表
          const accessRoutes = await store.dispatch('permission/GenerateRoutes', { token, ...res });
          // dynamically add accessible routes
          resetRouter();
          router.addRoutes(accessRoutes);

          // 请求带有 redirect 重定向时，登录自动重定向到该地址
          const redirect = decodeURIComponent(from.query.redirect || to.path);
          if (to.path === redirect) {
            // set the replace: true so the navigation will not leave a history record
            next({ ...to, replace: true });
          } else {
            // 跳转到目的路由
            next({ path: redirect });
          }
        } catch (error) {
          notification.error({
            message: '错误',
            description: '请求用户信息失败，请重试'
          });
          // remove token and loginout to re-login
          await store.dispatch('user/Logout');
          next({ path: loginRoutePath, query: { redirect: to.fullPath } });
          NProgress.done();
        }
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next();
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } });
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // finish progress bar
});
